package com.zsl.picture.controller;

import com.zsl.picture.model.User;
import com.zsl.picture.service.UserService;
import com.zsl.picture.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/registration")
    public String regis(){
        return "registration";
    }

    /**
     * 注册用户
     * @return
     */
    @PostMapping("/registration")
    @ResponseBody
    public R regis(User user){
        if(userService.valid(user)!=null){
            return R.error("账号已存在");
        }
        user.setCreateTime(new Date());
        user.setCreatorId(1);
        user.setCreatorName("admin");
        userService.save(user);
        return R.ok("注册成功");
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * 登录
     * @param param
     * @param model
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public R login(User param, Model model){
        User user = userService.valid(param);
        if(user==null){
            return R.error("账号或密码错误");
        }
        return R.ok().put("user",user);
    }

    /**
     * 根据id查询
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/{id}")
    public String one(@PathVariable("id") Long id, Model model){
        User user = userService.getOne(id);
        model.addAttribute("user",user);
        return "test";
    }

    /**
     * 列表查询
     * @param model
     * @return
     */
    @GetMapping
    public String all(Model model){
        List<User> list = userService.info();
        model.addAttribute("list",list);
        return "test";
    }
}
